package com.x.xiaoshuo.manager;

import android.content.Context;
import android.text.TextUtils;

import com.x.service.entity.BookListsBean;
import com.x.service.entity.Chapter;
import com.x.service.entity.ChapterList;
import com.x.xiaoshuo.Constant;
import com.x.xiaoshuo.XApplication;
import com.x.xiaoshuo.utils.FileUtils;
import com.x.xiaoshuo.utils.SharedPreferencesUtil;
import com.x.xiaoshuo.utils.StringUtils;
import com.x.xiaoshuo.utils.ToastUtils;
import com.x.xiaoshuo.utils.XCache;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import timber.log.Timber;

public class CacheManager {

    private static CacheManager manager;

    public static CacheManager getInstance() {
        return manager == null ? (manager = new CacheManager()) : manager;
    }

    public List<String> getSearchHistory() {
        return SharedPreferencesUtil.getInstance().getObject(getSearchHistoryKey(), List.class);
    }

    public void saveSearchHistory(Object obj) {
        SharedPreferencesUtil.getInstance().putObject(getSearchHistoryKey(), obj);
    }

    private String getSearchHistoryKey() {
        return "searchHistory";
    }


    public List<BookListsBean> getCollectionList() {
        List<BookListsBean> list = (ArrayList<BookListsBean>) XCache.get(
                XApplication.getInstance()).getAsObject(getCollectionKey());
        return list == null ? null : list;
    }

    public int getCacheChapterCount(Context mContext, String bookId) {
        try {

            File file = FileUtils.getBookDir(bookId);
            if (file.exists() && file.isDirectory()) {
                File files[] = file.listFiles();
                if (files != null) {
                    return files.length;
                } else {
                    return 0;
                }
            }
        } catch (Exception e) {

        }
        return 0;
    }

    public void removeCollection(String bookListId) {
        List<BookListsBean> list = getCollectionList();
        if (list == null) {
            return;
        }
        for (BookListsBean bean : list) {
            if (bean != null) {
                if (TextUtils.equals(bean._id, bookListId)) {
                    list.remove(bean);
                    XCache.get(XApplication.getInstance()).put(getCollectionKey(), (Serializable) list);
                    break;
                }
            }
        }
    }

    public void addCollection(BookListsBean bean) {
        List<BookListsBean> list = getCollectionList();
        if (list == null) {
            list = new ArrayList<>();
        }
        for (BookListsBean data : list) {
            if (data != null) {
                if (TextUtils.equals(data._id, bean._id)) {
                    ToastUtils.showToast("已经收藏过啦");
                    return;
                }
            }
        }
        list.add(bean);
        XCache.get(XApplication.getInstance()).put(getCollectionKey(), (Serializable) list);
        ToastUtils.showToast("收藏成功");
    }

    private String getCollectionKey() {
        return "my_book_lists";
    }


    public List<ChapterList.BookChapter> getChapterList(Context mContext, String bookId) {
        Object obj = XCache.get(mContext).getAsObject(getChapterListKey(bookId));
        if (obj != null) {
            try {
                ChapterList data = (ChapterList) obj;
                List<ChapterList.BookChapter> list = data.chapters;
                if (list != null && !list.isEmpty()) {
                    return list;
                }
            } catch (Exception e) {
                XCache.get(mContext).remove(getChapterListKey(bookId));
            }
        }
        return null;
    }

    public void saveChapterList(Context mContext, String bookId, ChapterList data) {
        XCache.get(mContext).put(getChapterListKey(bookId), data);
    }

    public void removeTocList(Context mContext, String bookId) {
        XCache.get(mContext).remove(getChapterListKey(bookId));
    }

    private String getChapterListKey(String bookId) {
        return bookId + "-chapter";
    }

    public File getChapterFile(String bookId, int chapter) {
        File file = FileUtils.getChapterFile(bookId, chapter);
        if (file != null && file.length() > 50)
            return file;
        return null;
    }

    public void saveChapterFile(String bookId, int chapter, Chapter data) {
        File file = FileUtils.getChapterFile(bookId, chapter);
        FileUtils.writeFile(file.getAbsolutePath(), StringUtils.formatContent(data.body), false);
    }


    public synchronized String getCacheSize() {
        long cacheSize = 0;

        try {
            String cacheDir = Constant.BASE_PATH;
            cacheSize += FileUtils.getFolderSize(cacheDir);
            if (FileUtils.isSdCardAvailable()) {
                String extCacheDir = XApplication.getInstance().getExternalCacheDir().getPath();
                cacheSize += FileUtils.getFolderSize(extCacheDir);
            }
        } catch (Exception e) {
            Timber.e(e.toString());
        }

        return FileUtils.formatFileSizeToString(cacheSize);
    }


    public synchronized void clearCache(boolean clearReadPos, boolean clearCollect) {
        try {
            // 删除内存缓存
            String cacheDir = XApplication.getInstance().getCacheDir().getPath();
            FileUtils.deleteFileOrDirectory(new File(cacheDir));
            if (FileUtils.isSdCardAvailable()) {
                // 删除SD书籍缓存
                FileUtils.deleteFileOrDirectory(new File(Constant.PATH_DATA));
            }
            // 删除阅读记录（SharePreference）
            if (clearReadPos) {
                SharedPreferencesUtil.getInstance().removeAll();
            }
            // 清空书架
            if (clearCollect) {
                CollectionsManager.getInstance().clear();
            }
            // 清除其他缓存
            XCache.get(XApplication.getInstance()).clear();
        } catch (Exception e) {
            Timber.e(e.toString());
        }
    }

}
